package com.ruoyi.auth.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ruoyi.auth.form.WxAppLoginBody;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.SystemRoleConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteMaintainerEmployessVillageService;
import com.ruoyi.system.api.RemoteRealNameService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.app.MaintainerEmployeesVillage;
import com.ruoyi.system.api.model.RealNameAuthInfo;
import com.tdd.wx.users.config.DefaultWxUserConfig;
import com.tdd.wx.users.entity.WxUser;
import com.tdd.wx.users.mongo.WxUserHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Log4j2
@Api(tags = "运营端微信登录")
@RestController
@RequestMapping("wxApp")
public class WxAppLoginController {

    @Autowired
    private WxUserHandler wxUserHandler;
    @Autowired
    private RemoteRealNameService remoteRealNameService;
    @Autowired
    private RemoteMaintainerEmployessVillageService remoteMaintainerEmployessVillageService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;
    @Autowired
    DefaultWxUserConfig defaultWxUserConfig;

    @Autowired
    private RemoteUserService remoteUserService;


    @ApiOperation("运营端微信登录")
    @PostMapping("open/login")
    public R login(@RequestBody WxAppLoginBody dto){
        try {
            log.info("app授权登录参数====》"+JSONUtil.toJsonStr(dto));
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + dto.getAccessToken() + "&openid=" + dto.getOpenid();
            String resStr = HttpUtil.get(url);
            log.info(resStr);
            JSONObject jo = JSONUtil.parseObj(resStr);
            String unionId = jo.getStr("unionid");
            WxUser wxUser = wxUserHandler.findByUnionId(unionId);
            if(wxUser == null){
                return R.fail("请先登录天蛙生态小程序！");
            }
            log.info("输入的授权码===》"+dto.getAuthCode());
            if(StrUtil.isNotEmpty(dto.getAuthCode())){
                log.info("redis授权码是否存在===》"+redisService.hasKey("auth_code_"+dto.getAuthCode()));
                if(!redisService.hasKey("auth_code_"+dto.getAuthCode())){
                    return R.fail(501,"授权码无效！");
                }
                Long maintainerUserId = redisService.getCacheObject("auth_code_"+dto.getAuthCode());
//                String villageCodes = MapUtil.getStr(redisMap,"villageCodes",null);
                System.out.println("id=====>>"+maintainerUserId);
                System.out.println("判断====>"+(maintainerUserId==null));
                if(maintainerUserId == null){
                    return R.fail("授权码无效！");
                }
                R<List<MaintainerEmployeesVillage>> resR = remoteMaintainerEmployessVillageService.findEUidAndMid(unionId,maintainerUserId,SecurityConstants.INNER);
                if(resR.getData().size()==0){
                    remoteMaintainerEmployessVillageService.save(unionId,maintainerUserId,null,SecurityConstants.INNER);
                }
                /**
                 * 创建员工账号
                 * songping
                 */
                R<RealNameAuthInfo> infoResult = remoteRealNameService.findByUnionIdAndType(unionId,10L, SecurityConstants.FROM_SOURCE);
                if(infoResult.getData() != null){
//                    R.fail("该用户:{}已成为服务商角色,无法成为服务商员工角色",wxUser.getNickName());
                    log.info("该用户:{}已成为服务商角色,无法成为服务商员工角色",wxUser.getNickName());
                }else{
                    R<SysUser> byUnionid = remoteUserService.findByUnionid(unionId, SecurityConstants.INNER);
                    SysUser empUser = byUnionid.getData();
                    if(empUser == null ){
                        empUser = new SysUser();
                        empUser.setNickName(wxUser.getNickName());
                        empUser.setUserName(wxUser.getPhone());
                        empUser.setUnionId(wxUser.getUnionId());
                        empUser.setRoleIds(new Long[]{SystemRoleConstants.MAINTAINER_EMP_ROLE_ID});
                        empUser.setPhonenumber(wxUser.getPhone());
                        empUser.setPassword(SecurityUtils.encryptPassword(wxUser.getPhone()));
                        empUser.setAvatar(wxUser.getAvatar());
                        if(StrUtil.isNotEmpty(wxUser.getGener())){
                            switch(wxUser.getGener()){
                                case "0":
                                    empUser.setSex("2");
                                    break;
                                case "1":
                                    empUser.setSex("0");
                                    break;
                                case "2":
                                    empUser.setSex("1");
                                    break;
                                default:
                                    empUser.setSex("2");
                                    break;
                            }
                        }
                        empUser.setStatus("1");
                        R<SysUser> userR = remoteUserService.addSysUser(empUser);
                        wxUser.setSysUserId(userR.getData().getUserId());

                    }else{
                        wxUser.setSysUserId(empUser.getUserId());
                    }
                    wxUser.setSysUserName(empUser.getUserName());
                    log.info("员工账户信息为:{}",new Gson().toJson(empUser));
                }
                // 更新 wxUser 到 mongodb 中
                wxUserHandler.update(wxUser);
                /**
                 * 创建员工账号
                 * songping
                 */
                log.info("员工账户返回给前端的wxUser:{}",new Gson().toJson(wxUser));
                log.info("员工账户返回给前端的token:{}",tokenService.createWxToken(normlizeUser(wxUser)));
                return R.ok(tokenService.createWxToken(normlizeUser(wxUser)));
            }else {
                //查看是否认证 服务商
                R<RealNameAuthInfo> realNameAuthInfoResult = remoteRealNameService.findByUnionIdAndType(unionId,10L, SecurityConstants.FROM_SOURCE);
                if(realNameAuthInfoResult.getData() == null){
                    R<List<MaintainerEmployeesVillage>> resR = remoteMaintainerEmployessVillageService.findByEmployeesUnionid(unionId,SecurityConstants.INNER);
                    if(resR.getData() == null || resR.getData().size() == 0){
                        return R.fail("请先认证服务商！");
                    }
                    return R.ok(tokenService.createWxToken(normlizeUser(wxUser)));
                }
                log.info("服务商账户返回给前端的wxUser:{}",new Gson().toJson(wxUser));
                log.info("服务商账户返回给前端的token:{}",tokenService.createWxToken(normlizeUser(wxUser)));
                return R.ok(tokenService.createWxToken(normlizeUser(wxUser)));
            }

        } catch (Exception e) {
            log.error(e);
            return R.fail("登录失败！");
        }
    }

    private WxUser normlizeUser(WxUser user)
    {
        if(user.getSysUserId()==null)
        {
            user = defaultWxUserConfig.getDefaultUser(user);
        }
        return user;
    }



}
